package com.fzkj.nio.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * 客户端代码
 */
public class Client {
    private Selector selector;
    private SocketChannel sChannel;
    private static final int PORT = 2323;
    private static final String IP = "127.0.0.1";

    // 初始化客户端信息
    public Client(){
        init();
    }

    /**
     * 客户端初始化方法
     */
    private void init(){
        try {
            // 创建选择器
            selector = Selector.open();
            // 获取通道
            sChannel = SocketChannel.open(new InetSocketAddress(IP, PORT));
            // 切换为非阻塞模式
            sChannel.configureBlocking(false);
            // 监听读事件
            sChannel.register(selector, SelectionKey.OP_READ);
            System.out.println("客户端准备完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        // 定义一个线程监听消息
        new Thread(() -> {
            try{
                client.readInfo();
            }catch (Exception e){
                e.printStackTrace();
            }
        }).start();

        // 发消息
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()){
            String msg = sc.nextLine();
            client.sendMsg(msg);
        }
    }

    /**
     * 发送消息
     * @param msg
     */
    private void sendMsg(String msg) {
        try {
            sChannel.write(ByteBuffer.wrap(msg.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读客户端接收到的消息
     */
    private void readInfo() throws IOException{
        while(true){
            if (selector.select() > 0){
                Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                while(it.hasNext()){
                    SelectionKey sk = it.next();
                    if (sk.isReadable()){
                        // 拿到当前通道
                        SocketChannel sChannel = (SocketChannel) sk.channel();
                        // 拿到通道之后就要去获取通道中的缓冲区里面的数据
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        sChannel.read(buffer);
                        String msg = new String (buffer.array(), 0, buffer.remaining());
                        System.out.println("接收到消息：" + msg);
                    }
                    it.remove();
                }
            }
        }
    }
}
